﻿using SqlSugar;

namespace API.Service
{
    public class FieldTranslationService : IFieldTranslationService
    {
        ISqlSugarClient _db;

        public FieldTranslationService(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<Dictionary<string, string?>> GetFieldTranslationsAsync(string tableName)
        {
            // 使用SqlSugar内置的方法获取表的字段信息
            var tableInfoList =  _db.DbMaintenance.GetTableInfoList();

            // 查找指定表的信息
            var tableInfo = tableInfoList.FirstOrDefault(it => string.Equals(it.Name, tableName, System.StringComparison.OrdinalIgnoreCase));

            if (tableInfo == null || tableInfo.DbObjectType != DbObjectType.Table)
            {
                // 如果找不到指定表或不是表类型，可以抛出异常或返回空字典
                return new Dictionary<string, string?>();
            }

            // 获取表的列信息
            var columnInfos =  _db.DbMaintenance.GetColumnInfosByTableName(tableName);

            // 合并字段信息和翻译信息
            var fieldTranslations = columnInfos.ToDictionary(
                column => column.DbColumnName,
                column => !string.IsNullOrEmpty(column.ColumnDescription) ? column.ColumnDescription : column.DbColumnName
            );

            return fieldTranslations;

        }
    }
}
